import random
from captcha.image import ImageCaptcha

class ValidImgCode:
    def __init__(self):
        self.code_count = 5
    @staticmethod
    def getRandomStr():
        '''获取一个随机字符串，每个字符的颜色也是随机的'''
        random_num = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(97, 122))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
        return random_char

    def imgcode_captcha(self):
        image = ImageCaptcha(fonts=['/usr/share/fonts/truetype/Sarai/Sarai.ttf', '/usr/share/fonts/truetype/freefont/FreeSerif.ttf'])
        temp = []
        for i in range(self.code_count):
            # 循环5次，获取5个随机字符串
            random_char = self.getRandomStr()

            # 保存随机字符，以供验证用户输入的验证码是否正确时使用
            temp.append(random_char)
        valid_str = "".join(temp)
        image_end = image.generate(valid_str)

        return valid_str, image_end

